<template>
  <div>
    <el-card>
      <CategorySelector :disabled="!isShowAttrList"></CategorySelector>
    </el-card>
    <el-card style="margin-top: 10px">
      <template #header>
        <div class="card-header">
          <el-button @click="showAdd" :disabled="!categoryStore.cate3Id" class="button" type="primary"
            :icon="Plus">添加属性</el-button>
        </div>
      </template>
      <!-- 属性展示列表 -->
      <el-table v-if="isShowAttrList" v-loading="loading" :data="attrInfoList" border style="width: 100%">
        <el-table-column v-slot="{ $index }" label="序号" width="120">
          {{ $index + 1 }}
        </el-table-column>
        <el-table-column prop="attrName" label="属性名称" width="150" />
        <el-table-column v-slot="{ row }" label="属性值列表">
          <el-tag v-for="attr in row.attrValueList" :key="attr.id" class="ml-2" type="success"
            style="margin-right: 5px">{{ attr.valueName }}</el-tag>
        </el-table-column>
        <el-table-column v-slot="{ row }" label="操作" width="140">
          <el-button @click="handleEdit(row)" type="primary" :icon="Edit" size="small" title="编辑" />
          <el-popconfirm @confirm="handleDelete(row.id)" :title="`确定要删除 ${row.attrName} 吗?`">
            <template #reference>
              <el-button type="danger" :icon="Delete" size="small" title="删除" />
            </template>
          </el-popconfirm>
        </el-table-column>
      </el-table>

      <!-- 添加/修改属性 -->
      <div v-else>
        <div>
          <span style="margin-right:20px">属性名</span>
          <el-input v-model="attr.attrName" placeholder="请输入属性名" style="width: 200px"></el-input>
        </div>
        <div style="margin-top: 20px">
          <el-button @click="handleAddAttrValue" :disabled="!attr.attrName" :icon="Plus"
            type="primary">添加属性值</el-button>
          <el-button @click="isShowAttrList = true" type="default">取消</el-button>
        </div>
        <div style="margin-top: 20px">
          <el-table :data="attr.attrValueList" style="width: 100%">
            <el-table-column v-slot="{ $index }" label="序号" width="180">
              {{ $index + 1 }}
            </el-table-column>
            <el-table-column v-slot="{ row, $index }" label="属性值名称">
              <div @click="row.isEdit = true" v-if="!row.isEdit">
                {{ row.valueName }}
              </div>
              <el-input :ref="(input: any) => inputsRef[$index] = input" v-else @blur="handleAttrBlur(row, $index)"
                v-model="row.valueName" type="text" size="small" />
            </el-table-column>
            <el-table-column v-slot="{ $index }" label="操作">
              <el-button @click="handleDelAttrValue($index)" type="danger" :icon="Delete" size="small"></el-button>
            </el-table-column>
          </el-table>
        </div>
        <div style="margin-top: 20px">
          <el-button @click="saveAttrInfo" :disabled="isSaveDisabled" type="primary">保存</el-button>
          <el-button @click="isShowAttrList = true" type="default">取消</el-button>
        </div>
      </div>

    </el-card>
  </div>
</template>

<script lang="ts">
import { ref, onMounted, nextTick, reactive, computed, watch } from 'vue'
import { reqGetAttrInfoList, reqDeleteAttr, reqSaveAttrInfoList } from '@/api/product/attr'
import type { attrModel, attrListModel } from '@/api/product/model/attr'
import { Plus, Edit, Delete } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import cloneDeep from 'lodash/cloneDeep'
import { useCategoryStore } from '@/stores/category'
export default {
  name: 'attr'
}
</script>
<script setup lang="ts">
// 表格加载效果
const loading = ref(false)
// 添加/修改属性
const attr = reactive<attrModel>({
  attrName: '',
  attrValueList: [],
  categoryId: -1,
  categoryLevel: 3
})
const inputsRef = ref<HTMLInputElement[]>([])
const isShowAttrList = ref(true) // 是否是显示的属性列表
const attrInfoList = ref<attrListModel>([])
const categoryStore = useCategoryStore()

// 获取属性列表
const getAttrInfoList = async () => {
  // 开启加载效果loading
  loading.value = true
  const { cate1Id, cate2Id, cate3Id } = categoryStore
  attrInfoList.value = await reqGetAttrInfoList(cate1Id as number, cate2Id as number, cate3Id as number)
  // 关闭加载效果loading
  loading.value = false
}

// 监视 cate3Id 有值的时候才需要发送请求
watch(() => categoryStore.cate3Id, async (cate3Id) => {
  if (!cate3Id) {
    attrInfoList.value = []
    return
  }
  getAttrInfoList()
}, { immediate: true })

// 删除属性
const handleDelete = async (attrId: number) => {
  const res = await reqDeleteAttr(attrId)
  ElMessage.success('删除属性成功！')
  // 重新获取数据
  getAttrInfoList()
}
// 编辑属性，显示编辑页面
const handleEdit = (row: attrModel) => {
  // 保存要更新的 attr
  Object.assign(attr, cloneDeep(row))

  // 显示更新页面
  isShowAttrList.value = false
}
// 显示添加页面
const showAdd = () => {
  // 重置attr
  delete attr.id  // 需要删除id，不然会覆盖掉上次的属性
  Object.assign(attr, {
    attrName: '',
    attrValueList: [],
    categoryId: categoryStore.cate3Id as number,
    categoryLevel: 3
  })

  // 显示添加页面
  isShowAttrList.value = false
}
// 添加属性值名称
const handleAddAttrValue = () => {
  attr.attrValueList.push({ valueName: '', attrId: attr.id, isEdit: true })
  nextTick(() => {
    // 获取焦点
    inputsRef.value[attr.attrValueList.length - 1].focus()
  })
}
// 删除属性值名称
const handleDelAttrValue = (index: number) => {
  attr.attrValueList.splice(index, 1)
}

// 计算保存按钮是否是禁用
const isSaveDisabled = computed(() => {
  const { attrName, attrValueList } = attr
  const hasName = !!attrName
  const hasValue = attrValueList.some(attrValue => attrValue.valueName)
  // 属性名称 和 属性值列表都必须有值
  return !hasName || !hasValue
})

// 保存属性值信息
const saveAttrInfo = async () => {
  // 删除掉后台不需要的 isEdit 属性
  attr.attrValueList.forEach(attrValue => delete attrValue.isEdit)

  // 发请求，保存属性
  await reqSaveAttrInfoList(attr)
  ElMessage.success('保存属性成功！')
  // 回到显示属性列表
  isShowAttrList.value = true
  // 重新获取列表显示
  getAttrInfoList()
}
// 输入框失去焦点
const handleAttrBlur = (row: any, index: number) => {
  if (!row.valueName) {
    // 如果内容为空，则删除此项
    attr.attrValueList.splice(index, 1)
    return
  }
  // 变为查看模式
  row.isEdit = false
}

</script>

<style lang="scss" scoped>
.el-select-dropdown .empty {
  color: #888;
  text-align: center;
  line-height: 4em;
}
</style>